﻿using System;
using System.Runtime.Serialization;
using System.Security.Permissions;
using InfiniTec.Exchange.Notifications.Microsoft.Exchange.WebServices;


namespace InfiniTec.Exchange.Notifications
{
	/// <summary>
	/// Contains a reference to a specific mailbox on an Exchange 2007 server.
	/// </summary>
	[Serializable]
	public sealed class MailboxReference: ISerializable
	{
		/// <summary>
		/// Gets or sets the address of the user. 
		/// </summary>
		/// <value>The address.</value>
		public string Address { get; private set; }
		/// <summary>
		/// Gets or sets the routing type of the <see cref="Address"/> property, e.g. SMTP for a standard email address.
		/// </summary>
		/// <value>The type of the routing.</value>
		public string RoutingType { get; private set; }

		/// <summary>
		/// Initializes a new instance of the <see cref="MailboxReference"/> class.
		/// </summary>
		/// <param name="address">The address.</param>
		/// <param name="routingType">The routing type of the <paramref name="address"/> parameter.</param>
		public MailboxReference(string address, string routingType)
		{
			if (string.IsNullOrEmpty(routingType)) throw new ArgumentNullException("routingType");
			if (string.IsNullOrEmpty(address)) throw new ArgumentNullException("address");

			Address = address;
			RoutingType = routingType;
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailboxReference"/> class.
		/// </summary>
		/// <param name="address">The email address (SMTP) of the user.</param>
		public MailboxReference(string address): this(address, "SMTP")
		{
		}

		/// <summary>
		/// Initializes a new instance of the <see cref="MailboxReference"/> class.
		/// </summary>
		/// <param name="address">The address.</param>
		internal MailboxReference(EmailAddressType address)
		{
			if (address == null) throw new ArgumentNullException("address");
			Address = address.EmailAddress;
			RoutingType = address.RoutingType;
		}

		/// <summary>
		/// Toes the ews mailbox.
		/// </summary>
		/// <returns></returns>
		internal EmailAddressType ToEwsMailbox()
		{
			return new EmailAddressType
			       	{
			       		EmailAddress = Address,
			       		RoutingType = RoutingType
			       	};
		}

		[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.SerializationFormatter)]
		void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
		{
			info.AddValue("Address", Address);
			info.AddValue("RoutingType", RoutingType);
		}

		private MailboxReference(SerializationInfo info, StreamingContext context)
		{
			Address = info.GetString("Address");
			RoutingType = info.GetString("RoutingType");
		}
	}
}
